package com.xzq.erp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.xzq.erp.domain.po.Product;
import com.xzq.erp.domain.po.WarehouseStockRecord;
import com.xzq.erp.domain.vo.WarehouseStockRecordVO;
import com.xzq.erp.mapper.ProductMapper;
import com.xzq.erp.mapper.WarehouseStockRecordMapper;
import com.xzq.erp.service.IWarehouseStockRecordService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 * 仓库出入库记录表 服务实现类
 * </p>
 *
 * @author xzq
 * @since 2025-06-04
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class WarehouseStockRecordServiceImpl extends ServiceImpl<WarehouseStockRecordMapper, WarehouseStockRecord> implements IWarehouseStockRecordService {

    private final ProductMapper productMapper;

    @Override
    public List<WarehouseStockRecordVO> getWarehouseStockRecordById(Long id) {
        List<WarehouseStockRecord> list = lambdaQuery()
                .eq(WarehouseStockRecord::getWarehouseId, id)
                .list();
        List<WarehouseStockRecordVO> vos = BeanUtil.copyToList(list, WarehouseStockRecordVO.class);
        List<Long> productIds = list.stream().map(WarehouseStockRecord::getProductId).toList();
        if(CollectionUtils.isEmpty(productIds)){
            return vos;
        }
        Map<Long, Product> productMap = productMapper.selectBatchIds(productIds).stream()
                .collect(Collectors.toMap(Product::getId, product -> product));
        for(WarehouseStockRecordVO vo : vos){
            Product product = productMap.get(vo.getProductId());
            if(Objects.isNull(product)){
                continue;
            }
            vo.setProductName(product.getName());
        }
        return vos;
    }
}
